import { Injectable } from '@nestjs/common';
import { User } from '../user/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Log } from './entities/log.entity';
import { Producer } from '@nestjs/microservices';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class LogService {
  constructor(
    @InjectRepository(Log) private readonly logRepository: Repository<Log>,
    private readonly producer: Producer,
  ) {}

  async logLogin(user: User): Promise<void> {
    const log = new Log();
    log.id = uuidv4();
    log.userId = user.id;
    log.username = user.username;
    log.timestamp = new Date();
    await this.logRepository.save(log);
    await this.producer.send({
      topic: 'LOGIN-MESSAGE',
      messages: [{ value: JSON.stringify(log) }],
    });
  }

  async findByUserId(userId: number): Promise<Log[]> {
    return this.logRepository.find({
      where: { userId },
      order: { timestamp: 'DESC' },
    });
  }
}
